package com.accgm.api.common;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.FormTag;
import org.htmlparser.tags.InputTag;
import org.htmlparser.tags.OptionTag;
import org.htmlparser.tags.SelectTag;
import org.htmlparser.tags.TextareaTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.accgm.api.utils.LogUtils;

public class WebForm {

	private FormTag formTag = null;

	private URI uri = null;

	private String charset = "gb2312";

	private HashMap inputMap = null;

	private String actionPath = "";

	public WebForm(String charset) {
		this.charset = charset;
		this.inputMap = new HashMap();
	}

	public WebForm(FormTag formTag, URI uri, String charset) {
		this.formTag = formTag;
		this.uri = uri;
		this.charset = charset;
		this.inputMap = new HashMap();

		if (formTag != null) {
			actionPath = formTag.getAttribute("action");

			if (actionPath == null)
				actionPath = "";

			// 鍙栧緱鎵�湁input
			NodeList nodeList = formTag.getFormInputs();
			for (int i = 0; i < nodeList.size(); i++) {
				InputTag input = (InputTag) nodeList.elementAt(i);
				String type = input.getAttribute("type");
				String name = input.getAttribute("name");
				String value = input.getAttribute("value");
				if (value == null) {
					value = "";
				}

				// 澶勭悊checkbox
				boolean isCheckBoxValue = true;
				if ("checkbox".equals(type)) {
					if (input.getText().indexOf(" checked") > 0) {
						isCheckBoxValue = true;
					} else {
						isCheckBoxValue = false;
					}
				}

				if (name != null && isCheckBoxValue) {
					inputMap.put(name, value);
					LogUtils.log.info(input.getAttribute("name") + "="
							+ input.getAttribute("value"));
				}
			}

			nodeList = formTag.getFormTextareas();
			for (int i = 0; i < nodeList.size(); i++) {
				TextareaTag input = (TextareaTag) nodeList.elementAt(i);
				String name = input.getAttribute("name");
				String value = input.getValue();
				if (value == null) {
					value = "";
				}

				if (name != null) {
					inputMap.put(name, value);
					LogUtils.log.info(input.getAttribute("name") + "="
							+ input.getAttribute("value"));
				}
			}

			// 鍙栧緱select
			NodeList list = formTag.searchFor(SelectTag.class, true);
			// LogUtils.log.info(" selec count:"+list.size());
			for (int i = 0; i < list.size(); i++) {
				// LogUtils.log.info(" selec :"+list.elementAt(i).toHtml());

				SelectTag select = (SelectTag) list.elementAt(i);
				NodeList optionList = select.searchFor(OptionTag.class, true);
				// LogUtils.log.info("select ..."+select.toHtml());
				for (int j = 0; optionList != null && j < optionList.size(); j++) {
					OptionTag op = (OptionTag) optionList.elementAt(j);
					if (op.toHtml().toLowerCase().indexOf("selected") > 0
							|| optionList.size() == 1) {
						String name = select.getAttribute("name");
						String value = op.getValue();
						if (name != null)
							inputMap.put(name, value);
						LogUtils.log.info(name + "=" + value);
						break;
					}
				}
			}

		}
	}

	/**
	 * 鏇挎崲input鍊�
	 * 
	 * @param name
	 * @param value
	 */
	public void replaceField(String name, String value) {
		inputMap.put(name, value);
	}

	/**
	 * 鍙栧嚭input鍊�
	 * 
	 * @param name
	 * @return
	 */
	public String getSingleFieldValue(String name) {
		String value = (String) inputMap.get(name);
		return value;
	}

	/**
	 * return NameValuePair list
	 * 
	 * @return
	 */
	public List<NameValuePair> getParamsList() {
		ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();

		Iterator iterator = inputMap.keySet().iterator();

		while (iterator.hasNext()) {
			String name = (String) iterator.next();
			String value = (String) inputMap.get(name);
			if (value == null)
				value = "";
			if (name != null)
				paramList.add(new BasicNameValuePair(name, value));
		}

		return paramList;
	}

	/**
	 * 鍙傛暟瀛楃涓�
	 * 
	 * @return
	 */
	public String toParamString() {
		StringBuffer sb = new StringBuffer();
		Iterator iterator = inputMap.keySet().iterator();

		while (iterator.hasNext()) {
			String name = (String) iterator.next();
			String value = (String) inputMap.get(name);
			if (value == null)
				value = "";
			if (sb.length() != 0)
				sb.append('&');
			sb.append(name).append('=').append(value);
		}

		return sb.toString();
	}

	/**
	 * 鐪熶釜URL锛屽寘鎷弬鏁颁覆
	 * 
	 * @return
	 */
	public String toURLString() {
		String url = "";
		if (actionPath.indexOf('?') > -1) {
			url = actionPath + '&' + toParamString();
		} else {
			url = actionPath + '?' + toParamString();
		}

		return url;
	}

	/**
	 * 濉〃鍗�
	 */
	public void fillFormValue(Map paramsMap) {
		if (paramsMap == null)
			return;

		Iterator iterator = paramsMap.keySet().iterator();

		while (iterator.hasNext()) {
			String name = (String) iterator.next();
			String value = (String) paramsMap.get(name);
			if (value == null)
				value = "";
			replaceField(name, value);
		}
	}

	public FormTag getFormTag() {
		return formTag;
	}

	public void setFormTag(FormTag formTag) {
		this.formTag = formTag;
	}

	public URI getUri() {
		return uri;
	}

	public void setUri(URI uri) {
		this.uri = uri;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public String getActionPath() {
		return actionPath;
	}

	public void setActionPath(String actionPath) {
		this.actionPath = actionPath;
	}

	public static void main(String[] args) {
		Parser parser = Parser
				.createParser(
						"<form><input id=\"i1\"/><br/><div><select id=\"s1\"><option selected value=\"v111\">t111</option><option value=\"v222\">t222</option></select></div></form>",
						"gb2312");
		NodeList nodeList = null;

		FormTag formTag = null;
		try {
			nodeList = parser.parse(new NodeClassFilter(FormTag.class));

			formTag = (FormTag) nodeList.elementAt(0);

			NodeList list = formTag.searchFor(SelectTag.class, true);
			LogUtils.log.info("size=" + list.size());
			for (int i = 0; i < list.size(); i++) {

				SelectTag select = (SelectTag) list.elementAt(i);
				NodeList optionList = select.searchFor(OptionTag.class, true);
				for (int j = 0; optionList != null && j < optionList.size(); j++) {
					OptionTag op = (OptionTag) optionList.elementAt(j);
					if (op.toHtml().toLowerCase().indexOf("selected") > 0) {
						LogUtils.log.info(op.getValue());
						break;
					}

				}

			}
		} catch (ParserException e) {
			e.printStackTrace();
		}
	}

}
